package com.test;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;

public class PreviewCallbacker extends Thread implements PreviewCallback{

	final private Socket socket;
	final private String TAG = "PreviewCallbacker";
	final private AndroidSocketConnect context;
	private boolean closed;
	
	PreviewCallbacker (Socket socket, AndroidSocketConnect context){
		this.socket = socket;
		this.context = context;
		closed = false;
	}
	@Override
	public void onPreviewFrame(byte[] data, Camera camera) {
		Log.v(TAG, "AndroidSocketConnect onPreviewFrame");
		Log.v(TAG, "AndroidSocketConnect data.length = "+data.length);
		try {
			if(socket!=null && closed==false){
				Camera.Parameters parameters = camera.getParameters();
				int format = parameters.getPreviewFormat();

				int w = parameters.getPreviewSize().width;
				int h = parameters.getPreviewSize().height;
				// Get the YuV image
				YuvImage yuv_image = new YuvImage(data, format, w, h, null);

				Rect rect = new Rect(0, 0, w, h);
				sendThroughSocket(yuv_image, rect);

				//add the byte buffer back to the camera
				//camera.addCallbackBuffer(data);
				//Log.v(TAG, "AndroidSocketConnect addCallbackBuffer");
			}
		} 
		catch (IOException e) {
			close();
			context.close();
		}
		

	}
	public synchronized void sendThroughSocket(YuvImage image, Rect rect) throws IOException{
		Log.v(TAG, "AndroidSocketConnect sendThroughSocket");
		if(
				closed == false
				&& socket!=null
				&& !socket.isClosed() ){
			Log.v(TAG, "AndroidSocketConnect compressing image to JPEG and outputting");
			try{
				image.compressToJpeg(rect, 100, socket.getOutputStream());
			}
			catch(SocketException e){
				//TODO: properly catch SocketException to shut down activity when the socket is disconnected
				Log.v(TAG, "AndroidSocketConnect SocketException");
				close();
				context.close();
			}
		}
	}
	public synchronized void close(){
		closed = true;
	}

}
